﻿using IDAdmin.Common;
using IDAdmin.Lib.DataLayer;
using IDAdmin.Lib.UI;
using IDAdmin.Lib.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IDAdmin.Pages
{
    public partial class LoginDataStatistics : BasePage
    {
        public LoginDataStatistics()
            : base(Lib.AppFunctions.LOGINDATASTATISTICS)
        {

        }
        protected override void Page_Load(object sender, EventArgs e)
        {
            if (!IsLogin())
            {
                RedirectToLogOn();
            }
            else if (!CheckRight())
            {
                RedirectToDeniedMessage();
            }
            if (!IsPostBack)
            {
                List<Server> listserver = WebDB_N.ListServer();
                ListItem l1 = new ListItem("--Tất cả--", "0");
                ListSerrverDropDownList1.Items.Add(l1);
                foreach (var item in listserver)
                {
                    ListItem l = new ListItem(item.zonename.ToString(), item.gamezone.ToString());
                    ListSerrverDropDownList1.Items.Add(l);
                }  
            }                   
        }


        protected void countButton_Click(object sender, EventArgs e)
        {
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            dataPanel.Controls.Clear();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            if (ListSerrverDropDownList1.SelectedValue!=null)
            {
                dataPanel.Controls.Clear();
                dataPanel.Controls.Add(getStatsAu(dateTimeList, ListSerrverDropDownList1.SelectedValue));
            }
            else
            {
                dataPanel.Controls.Clear();
                dataPanel.Controls.Add(getStatsAu(dateTimeList,"0"));
            }     
            //dataPanel.Controls.Add(getStatsAu(dateTimeList));
            watch.Stop();
            double elapsedMS = watch.ElapsedMilliseconds;
            measureLB.Text = elapsedMS.ToString() + "miliseconds";
        }



        protected void Button1_Click(object sender, EventArgs e)
        {
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            dataPanel.Controls.Clear();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            SaveAuStats(dateTimeList[0].ToString("yyyy-MM-dd"));
            watch.Stop();
            double elapsedMS = watch.ElapsedMilliseconds;
            measureLB.Text = elapsedMS.ToString() + "miliseconds";
        }


        /// <summary>
        /// so lieu moi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        /// 

        private bool SaveAuStats(string day)
        {            
            bool b = WebDB_N.InsertStatsAU(day);
            return b;
        }

        private Table getStatsAu(List<DateTime> datetimeList,string server)
        {
            Table table = new Table();
            List<StatsAu> ListStatAuAll = WebDB_N.getStatsAu(datetimeList,server);
            table.CssClass = "table1";
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange(
                new TableCell[]
                {                     
                    UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),                  
                    UIHelpers.CreateTableCell("Dau",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Nau",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("A7",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("A30",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("LAU",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("L7%",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng số tài khoản thất thoát ngày này",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng tỷ lệ thất thoát",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Số tài khoản thất thoát tăng mới",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tỷ lệ thất thoát tăng mới",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Số lượng IP login",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Số lượng IP đăng ký mới",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                }
            );
            table.Rows.Add(rowHeader);
            try
            {
                if (ListStatAuAll == null || ListStatAuAll.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (var dr in ListStatAuAll)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {                                  
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.datetime),HorizontalAlign.Center,css),                                  
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.dau),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.nau),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.a7),HorizontalAlign.Center,css),
                                     UIHelpers.CreateTableCell(Converter.ToString(dr.a30),HorizontalAlign.Center,css),
                                      UIHelpers.CreateTableCell(Converter.ToString(dr.lau),HorizontalAlign.Center,css),
                                      UIHelpers.CreateTableCell(Converter.ToString(dr.l7percent) +"%",HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.alluserlossday),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.alluserlossdaypercent)+"%",HorizontalAlign.Center,css),
                         UIHelpers.CreateTableCell(Converter.ToString(dr.alluserlossnew),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.alluserlossnewpercent)+"%",HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.ipactive),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.ipactivenew),HorizontalAlign.Center,css)
                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return table;
        }




        ///cũ
        private Table getLoginData(List<Au> auData, List<Ccu> ccuData)
        {

            List<Au> auList = new List<Au>(auData.Count);
            auData.ForEach((item) =>
            {
                auList.Add(new Au(item));
            });
            //List<Ccu> ccuList = new List<Ccu>(ccuData.Count);
            //ccuData.ForEach((item) =>
            //{
            //    ccuList.Add(new Ccu(item));
            //});

            foreach (Au auItem in auList)
            {
                auItem.Timestamp = ConverterWorkData.truncateTime(auItem.Timestamp, "dd/MM/yyyy");
            }

            //foreach (Ccu ccuItem in ccuList)
            //{
            //    ccuItem.Timestamp = ConverterWorkData.truncateTime(ccuItem.Timestamp, "dd/MM/yyyy");
            //}

            List<string> timeList = new List<string>();
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            foreach (DateTime item in dateTimeList)
            {
                string timestamp = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(item, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                timeList.Add(timestamp);
            }
            timeList = timeList.OrderByDescending(o => o).ToList();

            //var acuSumList = dataList.GroupBy(c => c.Timestamp).Select(g => new { Timestamp = g.Key, Average = g.Average(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();

            List<LoginData> loginDataList = new List<LoginData>();
            //var pcuSumList = (from tb2 in (from tb in ccuList.AsParallel() group tb by new { tb.GameZone, tb.Timestamp } into grp select new { grp.Key.GameZone, grp.Key.Timestamp, Max = grp.Max(m => long.Parse(m.Num)) }).AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp, PcuSum = grp2.Sum(s => s.Max) }).ToList();
            //var pcuSumList = (from tb in ccuList group tb by new { tb.GameZone, tb.Timestamp } into grp select new { grp.Key.GameZone, grp.Key.Timestamp, Max = grp.Max(m => m.Num) }).ToList();
            //var temp = ccuList.Where(w => w.GameZone.Equals("2491372") && w.Timestamp.Equals("1423699200")).Max(m=>long.Parse(m.Num));

            //------coi lai------
            //var dauList = (from tb2 in (from tb in auList.AsParallel() group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp }).Distinct().AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp,Count = grp2.Count() });
            //var ipDauList = (from tb2 in (from tb in auList.AsParallel() group tb by new { tb.IP, tb.Timestamp } into grp select new { grp.Key.IP, grp.Key.Timestamp }).Distinct().AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp, Count = grp2.Count() });

            //var nauList=(from tb in auList )
            for (int i = 0; i < timeList.Count; i++)
            {
                //string strDt= ConverterWorkData.ConvertFromUnixTimestamp(long.Parse(timeList[i])).ToString("dd/MM/yyyy hh:mm");
                //DateTime dtTemp = DateTime.ParseExact(strDt, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);
                //string timeStampTemp = truncateSecond(timeList[i]);
                LoginData ld = new LoginData();
                var nau = "";
                string A7 = "";
                string A30 = "";

                var accountBeforeAtTimeList = (from tb in auList.AsParallel() where long.Parse(tb.Timestamp) < long.Parse(timeList[i]) select new { tb.Account }).Distinct().ToList();
                //var nauList = (from t1 in auList
                //where !(from t2 in accountBeforeAtTimeList select t2.Account).Contains(t1.Account) && t1.Timestamp.Equals(timeList[i])
                //select t1).GroupBy(g => g.Account);
                List<string> nauList = new List<string>();

                #region accountAtTimeList
                //var accountAtTimeList = (from tb in auList where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().ToList();
                var accountAtTimeList = new[] { new { Account = "" } }.ToList();
                accountAtTimeList.RemoveAt(0);
                foreach (var item in auList)
                {
                    if (item.Timestamp.Equals(timeList[i]))
                    {
                        accountAtTimeList.Add(new { Account = item.Account });
                    }
                }
                accountAtTimeList = accountAtTimeList.Distinct().ToList();

                #endregion

                if (accountBeforeAtTimeList.Count() != 0)
                {
                    foreach (var item in accountAtTimeList)
                    {
                        int numLoop = 0;
                        for (int k = 0; k < accountBeforeAtTimeList.Count(); k++)
                        {
                            if (item.Account.Equals(accountBeforeAtTimeList[k].Account))
                            {
                                break;
                            }
                            else
                            {
                                numLoop++;
                            }

                        }
                        if (numLoop == accountBeforeAtTimeList.Count())
                        {
                            nauList.Add(item.Account);
                        }
                    }

                }
                else
                    if (accountBeforeAtTimeList.Count() == 0)
                    {
                        foreach (var itemTemp in accountAtTimeList)
                        {
                            nauList.Add(itemTemp.Account);
                        }
                    }

                var ipBeforeAtTimeList = (from tb in auList.AsParallel() where long.Parse(tb.Timestamp) < long.Parse(timeList[i]) select new { tb.IP }).Distinct().ToList();
                List<string> ipNauList = new List<string>();

                #region ipAtTimeList
                //var ipAtTimeList = (from tb in auList where tb.Timestamp.Equals(timeList[i]) select new { tb.IP }).Distinct().ToList();
                var ipAtTimeList = new[] { new { IP = "" } }.ToList();
                ipAtTimeList.RemoveAt(0);
                foreach (var item in auList)
                {
                    if (item.Timestamp.Equals(timeList[i]))
                    {
                        ipAtTimeList.Add(new { IP = item.IP });
                    }
                }
                ipAtTimeList = ipAtTimeList.Distinct().ToList();
                #endregion

                if (ipBeforeAtTimeList.Count() != 0)
                {
                    foreach (var item in ipAtTimeList)
                    {
                        int numLoop = 0;
                        for (int k = 0; k < ipBeforeAtTimeList.Count(); k++)
                        {
                            if (item.IP.Equals(ipBeforeAtTimeList[k].IP))
                            {
                                break;
                            }
                            else
                            {
                                numLoop++;
                            }

                        }
                        if (numLoop == ipBeforeAtTimeList.Count())
                        {
                            ipNauList.Add(item.IP);
                        }
                    }

                }
                else
                    if (ipBeforeAtTimeList.Count() == 0)
                    {
                        foreach (var itemTemp in ipAtTimeList)
                        {
                            ipNauList.Add(itemTemp.IP);
                        }
                    }

                var accountToTime = (from tb in auList where tb.Timestamp.CompareTo(timeList[i]) <= 0 select new { tb.Account }).Distinct().ToList();
                if (nauList != null && nauList.Count() > 0)
                {
                    nau = nauList.Distinct().Count().ToString();
                }
                else
                {
                    nau = "";
                }
                //ld.Nau =  nauList.Distinct().Count().ToString();
                ld.Nau = nau;

                ld.IPActiveNew = ipNauList.Distinct().Count().ToString();

                /* try
                 {
                     var check = (from tb in timeList.AsParallel() where tb.CompareTo(timeList[i]) < 0 select tb).Count().ToString();

                     if (int.Parse(check) >= 7)
                     {
                         DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                         List<DateTime> sevenDayBeforeList = new List<DateTime>();
                         //sevenDayBeforeList.Add(dtTemp);
                         for (int j = 1; j <= 7; j++)
                         {
                             sevenDayBeforeList.Add(dtTemp.AddDays(-j));
                         }
                         List<List<string>> dauAtTimeList = new List<List<string>>();
                         var dauGroupAccountTimeStampList = (from tb in auList.AsParallel() group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp }).Distinct();
                         foreach (DateTime dtItem in sevenDayBeforeList)
                         {
                             string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                             dauAtTimeList.Add(dauGroupAccountTimeStampList.AsParallel().Where(w => w.Timestamp.Equals(dtCurrent)).Select(s => s.Account).Distinct().ToList());
                         }

                         List<string> unionSevenDayBefore = new List<string>();
                         foreach (List<string> item in dauAtTimeList)
                         {
                             //var listTemp = (from tb in item select tb);//.Union(from tb1 in unionDaySevenDayBefore select tb1).ToList();
                             foreach (var itemi in item)
                             {
                                 unionSevenDayBefore.Add(itemi);
                             }

                         }
                         A7 = unionSevenDayBefore.AsParallel().Distinct().Count().ToString();
                     }
                 }
                 catch (Exception ex)
                 {
                     A7 = "";
                 }*/

                DateTime atTimeTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                DateTime mondayOfweekDt;
                if ((int)atTimeTemp.DayOfWeek != 0)
                {
                    mondayOfweekDt = atTimeTemp.AddDays(-((int)atTimeTemp.DayOfWeek - 1));
                }
                else
                {
                    mondayOfweekDt = atTimeTemp.AddDays(-6);
                }
                string mondayOfweekTs = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(mondayOfweekDt, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                //if (((from tb in timeList where tb.CompareTo(mondayOfweekTs) == 0 select tb).Count() > 0) && timeList[i].CompareTo(mondayOfweekTs) >= 0)
                //{
                A7 = (from tb in auList.AsParallel() where tb.Timestamp.CompareTo(mondayOfweekTs) >= 0 && tb.Timestamp.CompareTo(timeList[i]) <= 0 select tb.Account).Distinct().Count().ToString();
                //}

                DateTime firstDayOfMonthDt = atTimeTemp.AddDays(-(atTimeTemp.Day - 1));
                string firstDayOfMonthTs = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(firstDayOfMonthDt, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                // if ((from tb in timeList where tb.CompareTo(firstDayOfMonthTs)==0 select tb).Count() > 0)
                //{
                A30 = (from tb in auList.AsParallel() where tb.Timestamp.CompareTo(firstDayOfMonthTs) >= 0 && tb.Timestamp.CompareTo(timeList[i]) <= 0 select tb.Account).Distinct().Count().ToString();
                //}

                /* try
                 {
                     var check = (from tb in timeList.AsParallel() where tb.CompareTo(timeList[i]) < 0 select tb).Count().ToString();

                     if (int.Parse(check) >= 30)
                     {
                         DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                         List<DateTime> thirtyDayBeforeList = new List<DateTime>();
                         //sevenDayBeforeList.Add(dtTemp);
                         for (int j = 1; j <= 30; j++)
                         {
                             thirtyDayBeforeList.Add(dtTemp.AddDays(-j));
                         }
                         List<List<string>> dauAtTimeList = new List<List<string>>();
                         var dauGroupAccountTimeStampList = (from tb in auList.AsParallel() group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp }).Distinct();
                         foreach (DateTime dtItem in thirtyDayBeforeList)
                         {
                             string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                             dauAtTimeList.Add(dauGroupAccountTimeStampList.AsParallel().Where(w => w.Timestamp.Equals(dtCurrent)).Select(s => s.Account).Distinct().ToList());
                         }

                         List<string> unionThirtyDayBefore = new List<string>();
                         foreach (List<string> item in dauAtTimeList)
                         {
                             //var listTemp = (from tb in item select tb);//.Union(from tb1 in unionDaySevenDayBefore select tb1).ToList();
                             foreach (var itemi in item)
                             {
                                 unionThirtyDayBefore.Add(itemi);
                             }

                         }
                         A30 = unionThirtyDayBefore.AsParallel().Distinct().Count().ToString();
                     }
                 }
                 catch (Exception ex)
                 {
                     A30 = "";
                 }*/

                //var dauList = (from tb2 in (from tb in auList.AsParallel() group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp }).AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp, Count = grp2.Count() });
                //var accountAtTimelist = (from tb in auList.AsParallel() where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().ToList();
                var checkDayNum = (from tb in timeList.AsParallel() where tb.CompareTo(timeList[i]) > 0 select tb).Count().ToString();
                if (int.Parse(checkDayNum) >= 7)
                {
                    DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                    List<DateTime> sevenDayAfterList = new List<DateTime>();
                    //sevenDayBeforeList.Add(dtTemp);
                    for (int j = 1; j <= 7; j++)
                    {
                        sevenDayAfterList.Add(dtTemp.AddDays(j));
                    }

                    //DateTime dtAtDaySeven = dtTemp.AddDays(-7);
                    //string timeStampAtDaySeven = truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtAtDaySeven, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                    int count = 0;
                    foreach (var item in accountAtTimeList)
                    {
                        int numLoop = 0;
                        foreach (DateTime dtItem in sevenDayAfterList)
                        {
                            string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                            var hasLogin = (from tb in auList.AsParallel() where tb.Account.Equals(item.Account) && tb.Timestamp.Equals(dtCurrent) select tb).Count().ToString();
                            if (int.Parse(hasLogin) <= 0)
                            {
                                numLoop++;
                            }
                        }
                        if (numLoop.Equals(7))
                        {
                            count++;
                        }
                    }
                    ld.LAU = count.ToString();
                }


                //  var pcuSum = pcuSumList.AsParallel().Where(w => w.Timestamp.Equals(timeList[i])).Select(s => s.PcuSum).FirstOrDefault().ToString();
                // ld.PcuSum = pcuSum;


                if (accountAtTimeList != null)
                {
                    ld.Dau = accountAtTimeList.Count().ToString();//dauList.AsParallel().Where(w => w.Timestamp.Equals(timeList[i])).FirstOrDefault().Count.ToString();
                }
                else
                {
                    ld.Dau = "";
                }

                if (ipAtTimeList != null)
                {
                    ld.IPActive = ipAtTimeList.Count().ToString(); //ipDauList.AsParallel().Where(w => w.Timestamp.Equals(timeList[i])).FirstOrDefault().Count.ToString();
                }
                else
                {
                    ld.IPActive = "";
                }

                if (string.IsNullOrEmpty(ld.Dau) == false && string.IsNullOrEmpty(ld.LAU) == false && int.Parse(ld.Dau) != 0)
                {
                    ld.L7Percent = ((int.Parse(ld.LAU) * 100) / int.Parse(ld.Dau)).ToString() + "%";
                }
                else
                {
                    ld.L7Percent = "";
                }

                try
                {
                    var checkDayN = (from tb in timeList.AsParallel() where tb.CompareTo(timeList[i]) < 0 select tb).Count().ToString();
                    //var sumNumAccountInStoreAtTime = (from tb in auList where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().Count().ToString();
                    if (int.Parse(checkDayN) >= 7)
                    {
                        DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                        List<DateTime> sevenDayBeforeList = new List<DateTime>();
                        //sevenDayBeforeList.Add(dtTemp);// has stratDate
                        for (int j = 1; j <= 7; j++)
                        {
                            sevenDayBeforeList.Add(dtTemp.AddDays(-j));
                        }

                        //List<List<string>> dauAtTimeList = new List<List<string>>();
                        //var dauGroupAccountTimeStampList = (from tb in auList group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp });
                        //var accountAtTimeList = (from tb in auList where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().ToList();
                        int sumNumAccountLossAtTime = 0;
                        foreach (var account in accountToTime)
                        {
                            int numLoop = 0;
                            foreach (DateTime dtItem in sevenDayBeforeList)
                            {

                                string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                                var count = (from tb in auList.AsParallel() where tb.Account.Equals(account.Account) && tb.Timestamp.Equals(dtCurrent) select tb.Account).Count().ToString();
                                if (int.Parse(count) <= 0)
                                {
                                    numLoop++;
                                }
                                //string dtCurrent = truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                                //dauAtTimeList.Add(dauGroupAccountTimeStampList.Where(w => w.Timestamp.Equals(dtCurrent)).Select(s => s.Account).ToList()
                            }
                            if (numLoop.Equals(7))
                            {
                                sumNumAccountLossAtTime++;
                            }
                        }
                        ld.SumNumAccountLoss = sumNumAccountLossAtTime.ToString();
                    }
                }
                catch (Exception ex)
                {
                    ld.SumNumAccountLoss = "";
                }

                try
                {
                    var checkDayN = (from tb in timeList.AsParallel() where tb.CompareTo(timeList[i]) > 0 select tb).Count().ToString();
                    //var sumNumAccountInStoreAtTime = (from tb in auList where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().Count().ToString();
                    if (int.Parse(checkDayN) >= 7)
                    {
                        DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                        List<DateTime> sevenDayAfterList = new List<DateTime>();
                        //sevenDayBeforeList.Add(dtTemp);// has stratDate
                        for (int j = 1; j <= 7; j++)
                        {
                            sevenDayAfterList.Add(dtTemp.AddDays(j));
                        }

                        //List<List<string>> dauAtTimeList = new List<List<string>>();
                        //var dauGroupAccountTimeStampList = (from tb in auList group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp });
                        //var accountAtTimeList = (from tb in auList where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().ToList();
                        int NumAccountLossIncreaseNewAtTime = 0;
                        foreach (var account in nauList)
                        {
                            int numLoop = 0;
                            foreach (DateTime dtItem in sevenDayAfterList)
                            {

                                string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                                var count = (from tb in auList.AsParallel() where tb.Account.Equals(account) && tb.Timestamp.Equals(dtCurrent) select tb.Account).Count().ToString();
                                if (int.Parse(count) <= 0)
                                {
                                    numLoop++;
                                }
                                //string dtCurrent = truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                                //dauAtTimeList.Add(dauGroupAccountTimeStampList.Where(w => w.Timestamp.Equals(dtCurrent)).Select(s => s.Account).ToList()
                            }
                            if (numLoop.Equals(7))
                            {
                                NumAccountLossIncreaseNewAtTime++;
                            }
                        }
                        ld.NumAccountLossIncreaseNew = NumAccountLossIncreaseNewAtTime.ToString();
                    }
                }
                catch (Exception ex)
                {

                }

                var inventoryAccountSum = accountToTime.Count().ToString();
                if (string.IsNullOrEmpty(ld.SumNumAccountLoss) == false && string.IsNullOrEmpty(ld.Dau) == false && int.Parse(inventoryAccountSum) != 0)
                {
                    ld.PercentAccountLoss = ((int.Parse(ld.SumNumAccountLoss) * 100) / (int.Parse(inventoryAccountSum))).ToString() + "%";
                }
                else
                {
                    ld.PercentAccountLoss = "";
                }

                if (string.IsNullOrEmpty(ld.NumAccountLossIncreaseNew) == false && string.IsNullOrEmpty(ld.Nau) == false && ld.Nau.Equals("0") == false)
                {
                    ld.PercentAccountLossIncreaseNew = ((int.Parse(ld.NumAccountLossIncreaseNew) * 100) / (int.Parse(ld.Nau))).ToString() + "%";
                }
                else
                {
                    ld.PercentAccountLossIncreaseNew = "";
                }
                ld.A30 = A30;
                ld.A7 = A7;
                ld.DateTime = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                ld.Date = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local).ToString("dd/MM/yyyy");
                ld.TimeStamp = long.Parse(timeList[i]);
                loginDataList.Add(ld);
            }
            //string startTime = timeList[0];

            //DataTable dt = ConverterWorkData.ToDataTable(loginDataList, 3, 0);

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                  //  UIHelpers.CreateTableCell("Tổng pcu",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Dau",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Nau",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("A7",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("A30",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("LAU",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("L7%",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng số tài khoản thất thoát ngày này",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng tỷ lệ thất thoát",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Số tài khoản thất thoát tăng mới",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tỷ lệ thất thoát tăng mới",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("IP active",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("IP active new",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (loginDataList == null || loginDataList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (var dr in loginDataList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Date),HorizontalAlign.Center,css),
                                  //  UIHelpers.CreateTableCell(Converter.ToString(dr.PcuSum),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Dau),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Nau),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.A7),HorizontalAlign.Center,css),
                                     UIHelpers.CreateTableCell(Converter.ToString(dr.A30),HorizontalAlign.Center,css),
                                      UIHelpers.CreateTableCell(Converter.ToString(dr.LAU),HorizontalAlign.Center,css),
                                      UIHelpers.CreateTableCell(Converter.ToString(dr.L7Percent),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.SumNumAccountLoss),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.PercentAccountLoss),HorizontalAlign.Center,css),
                         UIHelpers.CreateTableCell(Converter.ToString(dr.NumAccountLossIncreaseNew),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.PercentAccountLossIncreaseNew),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.IPActive),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(dr.IPActiveNew),HorizontalAlign.Center,css)

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        private Table getLau(List<Au> auData)
        {
            List<Au> auList = new List<Au>(auData.Count);

            auData.ForEach((item) =>
            {
                auList.Add(new Au(item));
            });

            foreach (Au auItem in auList)
            {
                auItem.Timestamp = ConverterWorkData.truncateTime(auItem.Timestamp, "dd/MM/yyyy");
            }

            List<string> timeList = new List<string>();
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            foreach (DateTime item in dateTimeList)
            {
                string timestamp = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(item, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                timeList.Add(timestamp);
            }
            timeList = timeList.OrderByDescending(o => o).ToList();

            //var acuSumList = dataList.GroupBy(c => c.Timestamp).Select(g => new { Timestamp = g.Key, Average = g.Average(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();

            List<LoginData> loginDataList = new List<LoginData>();
            //var pcuSumList = (from tb2 in (from tb in ccuList.AsParallel() group tb by new { tb.GameZone, tb.Timestamp } into grp select new { grp.Key.GameZone, grp.Key.Timestamp, Max = grp.Max(m => long.Parse(m.Num)) }).AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp, PcuSum = grp2.Sum(s => s.Max) }).ToList();
            //var pcuSumList = (from tb in ccuList group tb by new { tb.GameZone, tb.Timestamp } into grp select new { grp.Key.GameZone, grp.Key.Timestamp, Max = grp.Max(m => m.Num) }).ToList();
            //var temp = ccuList.Where(w => w.GameZone.Equals("2491372") && w.Timestamp.Equals("1423699200")).Max(m=>long.Parse(m.Num));

            //------coi lai------
            //var dauList = (from tb2 in (from tb in auList.AsParallel() group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp }).Distinct().AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp,Count = grp2.Count() });
            //var ipDauList = (from tb2 in (from tb in auList.AsParallel() group tb by new { tb.IP, tb.Timestamp } into grp select new { grp.Key.IP, grp.Key.Timestamp }).Distinct().AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp, Count = grp2.Count() });

            //var nauList=(from tb in auList )
            var lauList = new[] { new { Account = "", Date = "" } }.ToList();
            lauList.RemoveAt(0);
            for (int i = 0; i < timeList.Count; i++)
            {
                //string strDt= ConverterWorkData.ConvertFromUnixTimestamp(long.Parse(timeList[i])).ToString("dd/MM/yyyy hh:mm");
                //DateTime dtTemp = DateTime.ParseExact(strDt, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);
                //string timeStampTemp = truncateSecond(timeList[i]);
                LoginData ld = new LoginData();
                //var nau = "";
                // string A7 = "";
                //string A30 = "";

                //var accountBeforeAtTimeList = (from tb in auList.AsParallel() where long.Parse(tb.Timestamp) < long.Parse(timeList[i]) select new { tb.Account }).Distinct().ToList();
                //var nauList = (from t1 in auList
                //where !(from t2 in accountBeforeAtTimeList select t2.Account).Contains(t1.Account) && t1.Timestamp.Equals(timeList[i])
                //select t1).GroupBy(g => g.Account);
                List<string> nauList = new List<string>();

                #region accountAtTimeList
                //var accountAtTimeList = (from tb in auList where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().ToList();
                var accountAtTimeList = new[] { new { Account = "" } }.ToList();
                accountAtTimeList.RemoveAt(0);
                foreach (var item in auList)
                {
                    if (item.Timestamp.Equals(timeList[i]))
                    {
                        accountAtTimeList.Add(new { Account = item.Account });
                    }
                }
                accountAtTimeList = accountAtTimeList.Distinct().ToList();

                #endregion

                //var dauList = (from tb2 in (from tb in auList.AsParallel() group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp }).AsParallel() group tb2 by new { tb2.Timestamp } into grp2 select new { grp2.Key.Timestamp, Count = grp2.Count() });
                //var accountAtTimelist = (from tb in auList.AsParallel() where tb.Timestamp.Equals(timeList[i]) select new { tb.Account }).Distinct().ToList();
                var checkDayNum = (from tb in timeList.AsParallel() where tb.CompareTo(timeList[i]) > 0 select tb).Count().ToString();
                if (int.Parse(checkDayNum) >= 7)
                {
                    DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                    List<DateTime> sevenDayAfterList = new List<DateTime>();
                    //sevenDayBeforeList.Add(dtTemp);
                    for (int j = 1; j <= 7; j++)
                    {
                        sevenDayAfterList.Add(dtTemp.AddDays(j));
                    }

                    int count = 0;
                    foreach (var item in accountAtTimeList)
                    {
                        int numLoop = 0;
                        foreach (DateTime dtItem in sevenDayAfterList)
                        {
                            string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                            var hasLogin = (from tb in auList.AsParallel() where tb.Account.Equals(item.Account) && tb.Timestamp.Equals(dtCurrent) select tb).Count().ToString();
                            if (int.Parse(hasLogin) <= 0)
                            {
                                numLoop++;
                            }
                        }
                        if (numLoop.Equals(7))
                        {
                            count++;
                            lauList.Add(new { Account = item.Account, Date = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local).ToString("dd/MM/yyyy") });
                        }
                    }
                }
            }

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Date",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Account",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lauList == null || lauList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (var dr in lauList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Date),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Account),HorizontalAlign.Center,css),
                            }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        protected void ListSerrverDropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


    }
}